package com.belizer.demo.unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class UnsafeDemo {
    public static void main(String[] args) throws IllegalAccessException, NoSuchFieldException {
        Field unsafeField = Unsafe.class.getDeclaredFields()[0];
        unsafeField.setAccessible(true);
        Unsafe unsafe = (Unsafe) unsafeField.get(null);

        //准备对象
        Student zhangsan = new Student("zhangsan",19);

        //使用unsafe的 objectFieldOffset 获取字段偏移量
        //使用unsafe的 getInt 获取年龄
        Field field = Student.class.getDeclaredField("age");
        long ageOffset = unsafe.objectFieldOffset(field);
        int age = (Integer) unsafe.getObject(zhangsan, ageOffset);
        System.out.println("使用Unsafe的getInt获取的年龄：" + age);

        // //使用unsafe的 putInt 修改年龄
        unsafe.putObject(zhangsan,ageOffset,20);
        System.out.println("使用Unsafe的修改年龄后的zhangsan，" + zhangsan);
    }

    private static class Student{


        private String name;
        private Integer age;

        public Student(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }

}
